package tcp.filetransfer;

import handlers.FileHandler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Date;
import java.util.Calendar;

import tcp.request.DownloadRequest;

public class DownloadHandler implements Runnable{
	private Socket downloadSocket ;
	private FileHandler handler;
	
	
	public DownloadHandler(Socket socket, FileHandler handler) {
		this.downloadSocket = socket;
		this.handler = handler;
	}
	public void run() {
		long startTime = Calendar.getInstance().getTimeInMillis();
		String fileName = null;
		try {
			
			PrintWriter out = new PrintWriter(this.downloadSocket.getOutputStream(),true);
			BufferedReader in = new BufferedReader(new InputStreamReader(this.downloadSocket.getInputStream()));
			
			
			String inputLine = null;
			while((inputLine = in.readLine()) != null){
				
			    if(inputLine.equalsIgnoreCase("HELO FTDWN")){
			    	fileName = in.readLine();
			    	
			    	//Check the file exsists and then send OK
			    	if(handler.findFile(fileName)){
			    		out.println("OK");
			    		File fileToSend = handler.getFile(fileName);
			    		BufferedReader reader = new BufferedReader(new FileReader(fileToSend));
				    	String tempLine = null;
				    	while((tempLine = reader.readLine())!=null){
				    		out.println(tempLine);
				    	}
				    	out.println("EOF");
				    	inputLine = null;
			    	}else {
			    		out.println("NOFILE");
			    		break;
			    	}
			    				    	
			    }
				
			}
			out.close();
			this.downloadSocket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long endTime = Calendar.getInstance().getTimeInMillis();
		this.handler.provideStats(fileName, startTime, endTime);
	}

}
